import { createRequire } from 'module';
import { config } from '../config.js';
import { Buffer } from "buffer";
import { mysqlObj } from './mysql.js';

const require = createRequire(import.meta.url);
// const ws = require('nodejs-websocket');
const ws = require('ws');
const qs = require('querystring');
const url = require('url');

let count = 0;  // 每个连接到websocket的用户都有一个conn
var server;

function createWS(httpsServer) {
    server = new ws.Server({ server: httpsServer });
    server.on("connection", (conn, req) => {

        // 把传递过来的字符转化为对象
        let url_params_str = url.parse(req.url).query;
        let url_params_obj = qs.parse(url_params_str);

        conn.open_id = url_params_obj.open_id;
        console.log("创建wss服务成功!")
        conn.on("message", function (message) {
            console.log(message.toString(), 'mmmm')
            broadcast(message);
        })
        conn.on("error", () => {
            console.log("wss服务异常！");
        })
        conn.on("close", () => {
            console.log("wss服务断开!");
        })
    })
    return server;
}
function broadcast(msg) {
    // 这里无法达到判断msg解析后是对象
    /**
     * 如果msg是字符串，JSON.parse()解析会报错!!!!!!!!!
     */
    let str = msg.toString();
    try {
        let temp_obj = JSON.parse(str);
        if (Object.prototype.toString.call(temp_obj) == "[object Object]") {
            server.clients.forEach((element) => {
                if (element.open_id == temp_obj.other_open_id) {
                    let json = JSON.stringify(temp_obj);
                    element.send(json);
                }
            })
        }
    } catch (e) {
        console.log(`接收到的数据:${str}------不是一个json格式！`)
    }
}
function tempMessage() {

}
export const export_ws = {
    createWS: createWS,
    broadcast: broadcast,
    tempMessage: tempMessage
}